/**
 * $Id: Formatter.java 21 2006-09-16 20:48:07Z willi.w $
 */
package at.wwu.tunes2db.utils;

public class Formatter {

    private static final int HOUR_IN_MS = 60 * 60 * 1000;

    private static final int DAY_IN_MS = 24 * HOUR_IN_MS;
    
    public static String formatBytes(double amount) {
        return formatBytes(Math.round(amount));
    }

    public static String formatBytes(long amount) {
        long kbTreshold = 1024;
        long mbTreshold = 1024 * 1024 * 2;
        long gbTreshold = ((long) 1024 * 1024) * 1024 * 4;

        if (amount < 0) {
            return "0 B";
        } else if (amount < kbTreshold) {
            return amount + " B";
        } else if (amount < mbTreshold) {
            return Long.toString((long) (((double) amount / 1024))) + " KB";
        } else if (amount < gbTreshold) {
            return Long.toString((long) (((double) amount / (1024 * 1024)))) + " MB";
        } else {
            return Long.toString((long) (((double) amount / (1024 * 1024 * 1024)))) + " GB";
        }
    }
    
    public static String formatNumber(double amount) {
        return formatNumber(Math.round(amount));
    }

    public static String formatNumber(long amount) {
        long kTreshold = 1000;
        long mTreshold = 1000 * 1000 * 2;
        long gTreshold = ((long) 1000 * 1000) * 1000 * 4;

        if (amount < 0) {
            return "0";
        } else if (amount < kTreshold) {
            return "" + amount;
        } else if (amount < mTreshold) {
            return Long.toString((long) (((double) amount / 1024))) + " k";
        } else if (amount < gTreshold) {
            return Long.toString((long) (((double) amount / (1024 * 1024)))) + " mil.";
        } else {
            return Long.toString((long) (((double) amount / (1024 * 1024 * 1024)))) + " bil.";
        }
    }

    public static String formatMilliseconds(double time) {
        return formatMilliseconds(Math.round(time));
    }

    public static String formatMilliseconds(long time) {
        StringBuffer sb = new StringBuffer();
        if (time < 0) {
            sb.append("-");
        }
        long duration = Math.abs(time);
        if (duration < 1000) {
            return "0s";
        }
        if (duration > DAY_IN_MS) {
            sb.append(duration / DAY_IN_MS + "d");
            duration = duration % DAY_IN_MS;
        }
        if (duration > HOUR_IN_MS) {
            sb.append(duration / HOUR_IN_MS + "h");
            duration = duration % HOUR_IN_MS;
        }
        if (duration > 60000) {
            sb.append(duration / 60000 + "m");
            duration = duration % 60000;
        }
        if (duration > 1000) {
            sb.append(duration / 1000 + "s");
            duration = duration % 1000;
        }
        return sb.toString();
    }
}